﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace OneKillProcess
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            this.StartPosition = FormStartPosition.CenterScreen; //启动在屏幕中央
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //隐藏工具栏，暂时不用
            toolStrip1.Hide();

            Config configJson = ConfigUtil.GetConfigJson();
            List<BtnItem> jsonProcessList = configJson.ProcessList;
            InitBtnItem(jsonProcessList);

            //LoadConfig();
            flowLayoutPanel1.Dock = DockStyle.Fill;

            //flowLayoutPanel1
            //AddButtons();
        }

        private void AddButtons()
        {
            string everythingPath = @"C:\Applications\Everything\Everything.exe";
            string oCamPath = @"C:\Program Files (x86)\oCam\oCam.exe";
            string cmdPath = @"C:\Windows\System32\cmd.exe";
            AddButtonWithIcon(everythingPath, "Everything 按钮");
            AddButtonWithIcon(oCamPath, "oCam 按钮");
            AddButtonWithIcon(cmdPath, "cmd.exe");
        }

        private void AddButtonWithIcon(string filePath, string buttonText)
        {
            BtnItem btnItem = new BtnItem();
            btnItem.ProcessPath = filePath;
            btnItem.ButtonName = buttonText;

            if (!string.IsNullOrWhiteSpace(filePath) && File.Exists(filePath))
            {
                Button button = new Button();
                button.Text = buttonText;

                Icon icon = Icon.ExtractAssociatedIcon(filePath);
                button.Image = icon.ToBitmap();

                button.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;


                // 增大按钮的尺寸
                button.Size = new Size(100, 100);

                // 添加自定义属性来存储图标路径
                button.Tag = btnItem;

                button.Click += Button_Click;

                flowLayoutPanel1.Controls.Add(button);
            }
            else
            {
                //MessageBox.Show($"文件 {filePath} 不存在。");
                Button button = new Button();
                button.Text = buttonText;

                // 增大按钮的尺寸
                button.Size = new Size(100, 100);

                // 缩放图像以适应按钮大小
                //Image originalImage = OneKillProcess.Properties.Resources._2078;
                //Image resizedImage = new Bitmap(originalImage, button.Width, button.Height);
                //button.Image = resizedImage;

                button.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;

                // 添加自定义属性来存储图标路径
                button.Tag = btnItem;

                button.Click += Button_Click;

                flowLayoutPanel1.Controls.Add(button);
            }
        }


        private void Button_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            BtnItem btnItem = (BtnItem)button.Tag;
            //MessageBox.Show($"点击了按钮，图标路径: {filePath}");

            string processName = btnItem.ProcessName;

            if (string.IsNullOrWhiteSpace(processName))
            {
                if (!string.IsNullOrWhiteSpace(btnItem.ProcessPath))
                {
                    processName = Path.GetFileNameWithoutExtension(btnItem.ProcessPath);
                }
            }

            if (string.IsNullOrWhiteSpace(processName))
            {
                return;
            }

            foreach (var process in Process.GetProcesses())
            {
                if (process.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase))
                {
                    process.Kill();
                }
            }
        }

        private void addProcess_Click(object sender, EventArgs e)
        {
            using (var dialog = new InputDialog())
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string keyword = dialog.Keyword;
                    SearchProcess(keyword);
                }
            }
        }


        private void SearchProcess(string keyword)
        {
            foreach (var process in Process.GetProcesses())
            {
                if (process.ProcessName.Contains(keyword))
                {
                    MessageBox.Show(process.MainModule.FileName);
                }
            }
        }

        private void LoadConfig()
        {
            // 读取配置
            string[] keys = ConfigurationManager.AppSettings.AllKeys;
            if (keys.Length == 0)
            {
                string cmdPath = @"C:\Windows\System32\cmd.exe";
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                if (config.AppSettings.Settings["cmd"] == null)
                {
                    config.AppSettings.Settings.Add("cmd", cmdPath);
                }

                //config.AppSettings.Settings["setting1"].Value = "newValue1";
                config.Save(ConfigurationSaveMode.Modified);
                // 强制重新加载配置
                ConfigurationManager.RefreshSection("appSettings");

                // 输出修改后的配置值
                Console.WriteLine($"修改后 cmd (modified): {ConfigurationManager.AppSettings["cmd"]}");
            }

            foreach (string key in ConfigurationManager.AppSettings.AllKeys)
            {
                //Console.WriteLine(key);
                string value = ConfigurationManager.AppSettings[key];
                Console.WriteLine($"process: {key}: {value}");
                AddButtonWithIcon(value, key);
            }

            // string setting1 = ConfigurationManager.AppSettings["setting1"];
            // string setting2 = ConfigurationManager.AppSettings["setting2"];
            // // 输出读取的配置
            // Console.WriteLine($"Setting 1: {setting1}");
            // Console.WriteLine($"Setting 2: {setting2}");
        }

        private void InitBtnItem(List<BtnItem> jsonProcessList)
        {
            foreach (BtnItem btnItem in jsonProcessList)
            {
                //Console.WriteLine($"添加按钮 btnItem: {btnItem}");
                AddButtonWithIcon(btnItem);
            }
        }

        private void AddButtonWithIcon(BtnItem btnItem)
        {
            Button button = new Button();
            button.Text = btnItem.ButtonName;

            // 增大按钮的尺寸
            button.Size = new Size(100, 100);

            if (!string.IsNullOrWhiteSpace(btnItem.ProcessPath) && File.Exists(btnItem.ProcessPath))
            {
                Icon icon = Icon.ExtractAssociatedIcon(btnItem.ProcessPath);
                button.Image = icon.ToBitmap();
                button.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
            }

            // 添加自定义属性来存储图标路径
            button.Tag = btnItem;

            button.Click += Button_Click;

            flowLayoutPanel1.Controls.Add(button);
        }
    }
}